package com.shenmazong.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shenmazong.utils.ResultResponse;
import com.shenmazong.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author 军哥
 * @version 1.0
 * @description: gateway过滤器
 * @date 2022/6/22 16:27
 */

@Configuration
public class GatewayFilter implements GlobalFilter, Ordered {

    @Autowired
    RedisTemplate redisTemplate;

    private Mono<Void> tokenError(ServerHttpRequest request, ServerHttpResponse response) {
        String msg = "";

        ResultResponse result = ResultResponse.FAILED(403, "没有携带token");
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            msg = objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        DataBuffer dataBuffer = response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(dataBuffer));
    }

    /**
     * 全局过滤
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取Request、Response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 解决中文乱码问题
        HttpHeaders headers = response.getHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 打印输出URI
        String requestUrl = exchange.getRequest().getURI().getRawPath();
        System.out.println(requestUrl);
        System.out.println(request.getURI());

        // 添加白名单
        if(requestUrl.contains("/login")) {
            return chain.filter(exchange);
        }
        if(requestUrl.contains("/logoUpload")) {
            return chain.filter(exchange);
        }

        // 拦截
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)) {
            return tokenError(request, response);
        }

        // token续期
        TokenUtils tokenUtils = TokenUtils.token();
        int i = tokenUtils.parseToken(token);
        if(TokenUtils.SUCCESS != i) {
            return tokenError(request, response);
        }

        // token续期
        String role = tokenUtils.getClaim("role");
        if(role.equals("admin")) {
            String userId = tokenUtils.getClaim("id");
            String key = "login_sys_" + userId;
            redisTemplate.expire(key, 2, TimeUnit.MINUTES);
        }
        else if(role.equals("user")) {
            String userId = tokenUtils.getClaim("id");
            String key = "login_user_" + userId;
            redisTemplate.expire(key, 2, TimeUnit.MINUTES);
        }

        // 放行
        return chain.filter(exchange);
    }

    /**
     * 排序，越小越先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
